﻿using PARK.Dependency;
using PARK.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Threading.Tasks;
using PARK.Common.Helper;
using PARK.BussinCache.Entitys.Dto.EvtData;
using Newtonsoft.Json;
using PARK.Accessctl.Entitys;
using Mapster;
using PARK.BussinCache.Entitys.Entity;
using JNPF.Logging;
using PARK.BussinCache.Interfaces;

namespace PARK.BussinCache
{
    /// <summary>
    /// 业务实现：宇泛设备接口
    /// </summary>
    [ApiDescriptionSettings(Tag = "UniSdk", Name = "UniSdk", Order = 160)]
    [Route("api/[controller]")]
    public class UniEvtNtService : IDynamicApiController, ITransient
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly SqlSugarScope _db;
        private readonly IParkCacheRepository _parkCacheRepository;

        /// <summary>
        /// 初始化一个<see cref="UniEvtNtService"/>类型的新实例
        /// </summary>
        public UniEvtNtService(
            IHttpContextAccessor httpContextAccessor,
            ISqlSugarClient db,
            IParkCacheRepository parkCacheRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _db = (SqlSugarScope)db;
            _parkCacheRepository = parkCacheRepository;
        }

        #region 通知回调
        /// <summary>
        /// 通知回调
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("Notify")]
        [AllowAnonymous]
        [Consumes("application/x-www-form-urlencoded")]
        public async Task<dynamic> callbackNotify([FromForm] EventInput input)
        {
            try
            {
                if (input != null)
                {
                    new LoggEx().uniEvtlog(input.ToJson());
                }
                var _eventCode = input.eventCode;
                var _eventGuid = input.eventGuid;
                var _eventMsg = input.eventMsg.Replace(@"\", "");
                switch (_eventCode)
                {
                    case "101004": //识别记录上报
                        var _Evt101004 = JsonConvert.DeserializeObject<Evt101004>(_eventMsg);
                        _Evt101004.eventGuid = _eventGuid;
                        var _ret = await AddEvt101004(_Evt101004);
                        if (_ret)
                        {
                            //处理成功
                            return new { result = 1, code = "WO_SUS1000", msg = "successful operation!", data = "", success = "true" };
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                new LoggEx().errlog(ex.Message);
            }
            return new { regcode = 1, regmsg = "" };
        }
        /// <summary>
        /// 处理人脸识别事件
        /// </summary>
        /// <param name="_Evt101004"></param>
        /// <returns></returns>
        [NonAction]
        public async Task<bool> AddEvt101004(Evt101004 _Evt101004)
        {
            try
            {
                if (!string.IsNullOrEmpty(_Evt101004.deviceNo))
                {
                    //获取设备
                    var _device = await _db.Queryable<AccessCtlEntity>().Where(t => t.CtlSn == _Evt101004.deviceNo).ToListAsync();
                    if (_device != null && _device.Count > 0)
                    {
                        var entity = _Evt101004.Adapt<UniEvt101004Entity>();
                        //门禁信息
                        entity.CtlId = _device[0].CtlId;
                        entity.Ctlposition = _device[0].Ctlposition;
                        entity.DoorAreaId = _device[0].DoorAreaId;
                        entity.DoorAreaName = _device[0].DoorAreaName;
                        entity.IsAtt = _device[0].IsAtt;
                        entity.CompanyId = _device[0].CompanyId;
                        entity.CompanyName = _device[0].CompanyName;
                        if (!string.IsNullOrEmpty(entity.timestamp))
                        {
                            entity.timestampDate = new DateUt().GetDateTimeMilliseconds(Convert.ToInt64(entity.timestamp));
                        }
                        if (!string.IsNullOrEmpty(entity.showTime))
                        {
                            entity.showTimeDate = new DateUt().GetDateTimeMilliseconds(Convert.ToInt64(entity.showTime));
                        }
                        if (!string.IsNullOrEmpty(entity.executeTime))
                        {
                            entity.executeTimeDate = new DateUt().GetDateTimeMilliseconds(Convert.ToInt64(entity.executeTime));
                        }
                        entity.Create();
                        //入库
                        var tisOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                        if (tisOk > 0)
                        {
                            //入缓存
                            await _parkCacheRepository.SetEvt101004queue(entity);
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                new LoggEx().errlog("AddEvt101004->处理人脸识别事件:" + ex.Message);
            }
            return false;
        }
        DateTime ConvertTampToDateTime(double timeStamp)
        {
            DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timeStamp).ToLocalTime();
            string formattedDateTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
            return Convert.ToDateTime(formattedDateTime);
        }
        #endregion
    }
}
